package com.hylc.fengkong;

import android.util.Log;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

public class NetUtil {
    private static String TAG = "NetUtil";

    /**
     * get ip v4
     */
    public static String getIPV4() {
        String ip =  getIPAddress(true);
        Log.e(TAG,"ipv4:   "+ip);
        return ip;
    }

    /**
     * 从第一个非本地主机接口获取IP地址
     *
     * @param useIPv4 true =返回ipv4，false =返回ipv6
     * @return 地址或空字符串
     */
    public static String getIPAddress(boolean useIPv4) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface networkInterface : interfaces) {
                List<InetAddress> addresses = Collections.list(networkInterface.getInetAddresses());
                for (InetAddress address : addresses) {
                    if (!address.isLoopbackAddress()) {
                        String sAddr = address.getHostAddress();
                        boolean isIPv4 = sAddr.indexOf(':') < 0;
                        if (useIPv4) {
                            if (isIPv4) {
                                return sAddr;
                            }
                        } else {
                            if (!isIPv4) {
                                // 删除ip6区域后缀
                                int delim = sAddr.indexOf('%');
                                return delim < 0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
                            }
                        }
                    }
                }
            }
        } catch (Exception ignored) {
        }
        return "";
    }

}
